<!--
    group: 企业管理
    name: 企业入驻----签署协议
    url: /enterprise/modules/signSettled
-->
<template>
  <div style='height: 100%;'>
    <h3>{{ text }}</h3>

    <a-spin :spinning="spinning">
      <div class="m-vue-pdf">
        <!-- <div class="wrap">
          <div id="demo"></div>
        </div> -->
        <Pdf4H5New :pdfUrl="pdfUrl"></Pdf4H5New>
      </div>
    </a-spin>

    <div class="main_footer">
      <a-button type="primary" v-if="show" class="btnsLarge" @click="signStep">确认签署</a-button>
      <a-button type="primary" v-if="!show" class="btnsLarge" @click="nextToStep">下一步</a-button>
<!--      <a class="mLeft" @click="prevStep">返回上一步</a>-->
    </div>


    <!--短信弹层-->
    <a-modal
      v-model="signVisible"
      :destroyOnClose="true"
      :footer="null"
      @cancel="handleCancel"
    >
      <div style="margin-top: 20px;">
        <p>请输入{{ form.newPhone }}收到的验证码</p>
        <a-form-model ref="form" :model="form" :rules="rules"
                      :label-col="labelCol" :wrapper-col="wrapperCol"
        >
          <a-form-model-item required prop="captcha">
            <a-input v-model="form.captcha" size="large" style="max-width: 230px;" type="text" placeholder="验证码" autocomplete="off">
              <a-icon slot="prefix" type="mail" :style="{ color: '#022EA0' }"/>
            </a-input>
            <a-button type="primary" @click="send" size="large" style="margin-left:20px;" :disabled="disabledCodeBtn">{{codeText}}</a-button>
          </a-form-model-item>
          <a-form-model-item :wrapper-col="{ span: 18, offset: 6 }">
            <a-button type="primary" @click="nextStep">下一步</a-button>
          </a-form-model-item>
        </a-form-model>
      </div>
    </a-modal>

  </div>
</template>

<script>
import '@/utils/rem'  //rem
import '@/assets/css/enterprise.less'  //css
import Pdfh5 from "pdfh5";  // 这两个一定要引入
import "pdfh5/css/pdfh5.css"; // 这两个一定要引入， 这个是在加载时，顶部会出来一个加载进度条和一些其他的样式
import { requestApi } from '@/api/settledEnt'
import { getLoginTicket,inviteEntSgin } from "@/api/enterprise";
import { carriedParameters } from "@/utils/util";
import { ACCESS_TOKEN, USER_NAME,USER_INFO } from "@/store/mutation-types"
import Vue from "vue";
import Pdf4H5New from './../../MoveLayout/components/Pdf4H5_.vue'
export default {
  name: 'signSettled',
  components:{Pdf4H5New},
  props: ['undertakeData'],
  data(){
    return{
      pdfh5: null,
      labelCol: { span: 2 },
      wrapperCol: { span: 18 },
      pdfUrl: '',
      signVisible: false,
      form: {
        phone: '',
        captcha: ''
      },
      codeText: '获取验证码',
      disabledCodeBtn: false,
      rules:{
        captcha: [
          { required: true, message: '请输入验证码!' },
          { validator: this.validateEn }
        ]
      },
      token: null,   //token免登录
      spinning: true,
      text: '签署协议',
      show: true,  //展示是否可以签署
      ticket: '',  //用来获取token
      agreeId: ''  //合同id
    }
  },
  watch: {
    // undertakeData: {
    //   handler(val) {
    //     // this.agreeId
    //     // this.undertakeData.agreeId
    //     if(val && val.entId){
    //       this.getAgreeInfo(val.entId)
    //     }
    //   },
    //   deep: true,
    //   immediate: true
    // },
  },
  created() {
    this.ticket = carriedParameters(window.location.href,'ticket');
    this.agreeId = carriedParameters(window.location.href,'agreeId');
  },
  mounted() {
    if(!this.agreeId){
      this.invitingSign()  //邀请负责人线上签署
    } else {
      this.getMobileNumber()  //获取token
    }
  },
  methods:{
    /**
     * 暂时废弃
     * @param {*} entId
     */
    getAgreeInfo(entId){
      inviteEntSgin({entId}).then(res=>{
        if(res.code == 200){
          this.agreeId = res.result.agreeId
        }else{
          this.$message.warning(res.message);
        }
      })
    },
    //确认签署
    signStep(){
      this.signVisible = true;
    },
    //h5展示pdf
    h5FdfFun(pdfurl){
      console.log(pdfurl)
      // this.pdfh5 = new Pdfh5("#demo", {
      //   pdfurl: pdfurl, // pdf 地址，请求的地址需要为线上的地址，测试的本地的地址是不可以的
      //   lazy: true, // 是否懒加载
      //   withCredentials: true,
      //   renderType: "canvas",
      //   maxZoom: 3, //手势缩放最大倍数 默认3
      //   scrollEnable: true, //是否允许pdf滚动
      //   zoomEnable: true, //是否允许pdf手势缩放
      // });
    },
    //
    handleCancel(){
      this.signVisible = false;
    },
    //发送验证码
    send(){
      //请求接口
      let params = {};
      params.transCode='1001';
      params.phone= this.form.phone;
      requestApi('/agreeInfo/sendSignSMS','put',params,this.token).then(res => {
        if (res.success) {
          this.$message.success('发送成功');
          this.countDown(60);
        }else{
          this.$message.warning(res.message);
        }
      })

    },
    //下一步sign
    nextStep(){
      this.$refs['form'].validateField(['captcha'], (Error) => {
        if (!Error){
          let code = this.form.captcha;
          requestApi('/agreeInfo/checkSignSMS?code=' + code,'put','',this.token).then(res => {
            if (res.success) {
              if (res.result){
                this.signVisible = false;
                this.getSuccessDetails();  //执行签署完成
              }
            }else{
              this.$message.warning(res.message);
            }
          })
        }
      })
    },
    //上一步
    prevStep(){
      this.$emit('prevStep')
    },
    //邀请负责人线上签署
    invitingSign(){
      inviteEntSgin({entId:this.undertakeData.entId}).then(res=>{
        if(res.code == 200){
          // 您选择了电子签，请先完成渠道法人实名认证！
          if(res.result.status == 1){
            this.agreeId = res.result.agreeId;
            this.getMobileNumber()
          }else{
            this.$message.warning('您选择了电子签，请先完成渠道法人实名认证！');
          }
        }else{
          this.$message.warning(res.message);
        }
      })
    },
    //获取token
    getMobileNumber(){
      let params = {};
      params.ticket = this.undertakeData.ticket || this.ticket;
      getLoginTicket(params).then(res => {
        if (res.success) {
          if (res.result){
            //获取token
            this.token = res.result.token;
            // let userInfo = res.result.userInfo;
            //token获取成功后替换缓存内的token
            if(this.token){
              //Vue.ls.get(ACCESS_TOKEN)
              Vue.ls.set(ACCESS_TOKEN,res.result.token, 7 * 24 * 60 * 60 * 1000)
              // Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              // Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
            }
            this.getDetailsUrl(this.token);
            this.getPhone(this.token);
          }
        }else{
          this.$message.warning(res.message)
        }
      })
    },
    //获取url
    getDetailsUrl(token){
      let id = this.undertakeData.agreeId || this.agreeId;
      if(this.$IS.isNullOrUnDef(id) || this.$IS.isEmpty(id)){
        this.spinning = false;
        return false
      }
      requestApi('/agreeInfo/detail?id=' + id,'get','',token).then(res => {
        if (res.success) {
          if (res.result){
            this.pdfUrl = res.result.agreeUrl;
            this.spinning = false;

            //status  1待签约、2已邮寄（纸质版）、3已签约
            res.result.status == 3 ? this.show = false : this.show = true;
            res.result.status == 3 ? this.text = '预览协议' : this.text = '签署协议';
            // this.h5FdfFun(res.result.agreeUrl);
          }
        }else{
          this.$message.warning(res.message);
        }
      })
    },
    //获取用户手机号
    getPhone(token){
      requestApi('zx/usermgr/queryLoginUserInfo','post','',token).then(res => {
        if (res.success) {
          if (res.result && res.result.phone){
              let phone = res.result.phone;
              this.form.newPhone = phone.substr(0,3) + '****' + phone.substr(7);
              this.form.phone = phone;
          }
        }else{
          this.$message.warning(res.message);
        }
      })
    },
    //签署完成后调取详情再次查询
    getSuccessDetails(){
      let params = {};
      params.agreeInfoId = this.undertakeData.agreeId || this.agreeId;
      requestApi('/agreeInfo/signByTemplatePlus','post',params,this.token).then(res => {
        if (res.success) {
          // this.signVisible = false;
          this.getDetailsUrl(this.token);
        }else{
          this.$message.warning(res.message);
        }
      })
    },
    //跳转注册成功
    nextToStep(){
      this.$emit('nextStep');
    },
    //校验验证码
    validateEn(rule, value, callback){
      let reg = /^[0-9]+$/
      // 长度为6到18个字符
      if (value !== '' && !reg.test(value)) {
        callback('验证码格式不正确,只能为纯数字!')
      } else if (value !== '' && value.length != 6) {
        callback('长度为6位纯数字!')
      } else {
        callback()
      }
    },
    // 倒计时方法
    countDown(time) {
      if (time === 0) {
        this.disabledCodeBtn = false;
        this.codeText = "重新获取";
        return;
      } else {
        this.disabledCodeBtn = true;
        this.codeText = "再次获取" + time + "s";
        time--;
      }
      setTimeout(() => {
        this.countDown(time);
      }, 1000);
    },
  },
}
</script>

<style scoped lang="less">
h3{
  color: @color-smudge;
}
/deep/ .ant-spin-nested-loading{
  height: 78%;
}
.m-vue-pdf {
  width: 100%;
  height: 100%;
  overflow: hidden;
  border: 1px solid #4266E5;
  background-color: rfba(66,102,229,.8);
}

#demo {
  width: 100%;
  height: 100%;
}
/deep/.ant-form-item-children{
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
